package com.csrcb.service;

import com.csrcb.constant.EmsInfoUrlValue;
import com.csrcb.constant.ParamConstant;
import com.csrcb.dao.CalcTime;
import com.csrcb.dto.BankExamCerficate;
import com.csrcb.tools.HttpSendContent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname EMSService
 * @Description 获取邮件的信息
 * @Date 2020/12/16 16:53
 * @Created by gangye
 */
public class EMSService {
    private static Logger logger = LoggerFactory.getLogger(EMSService.class);

    //请求查询自己的邮寄状态信息
    public String getEmsInfo(){
        StringBuilder requestUrl = new StringBuilder();
        requestUrl.append(ParamConstant.EMSINFO_URL);
        logger.info("获取邮寄信息状态的请求的路由:{}",requestUrl.toString());
        //设置请求头信息，请求信息在请求头中
        Map<String,String> headInfo = new HashMap<>();
        headInfo.put("Token",EmsInfoUrlValue.getQueryemstoken());
        String response = HttpSendContent.doGet(requestUrl.toString(),ParamConstant.ACCTYPE_TYPE_JSON ,headInfo);
        logger.info("返回报文:{}",response);
        return response;
    }

    //根据邮寄返回的报文获取邮寄状态，若为10未邮寄，若为20已邮寄，获取EMS邮寄单号
    public void boolEmsStatusForWeChatRemind(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        try {
            String emsData = getEmsInfo();
            String sendMessage;
            if (emsData == null || "".equals(emsData)){
                //定时任务，不能一直提醒，设置标识，提醒五次过期(程序退出)
                int errorTimes = Integer.valueOf(CalcTime.get(ParamConstant.HEAD_ERROR_TIME));
                if (errorTimes >= 5){
                    sendMessage = "时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
                        +"\n提醒结束，程序结束，修改请求头信息后再启动！";
                    new WeChatService().sendMessageWithToken(sendMessage);
                    logger.info("提醒结束，程序结束，修改请求头信息后再启动！");
                    System.exit(0);
                } else{
                    sendMessage = "查询证书的请求头信息过期\n"
                            + "时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    boolean flag = new WeChatService().sendMessageWithToken(sendMessage);
                    if (!flag){
                        EmailSendService.sendQqEmailforWeChatFail(false,null);
                    }
                    CalcTime.update(ParamConstant.HEAD_ERROR_TIME,String.valueOf(errorTimes+1));
                }
            }else{
                BankExamCerficate cerficate = objectMapper.readValue(emsData,BankExamCerficate.class);
                logger.info("返回报文ceficate的data信息:{}",cerficate.getData().get(0));
                logger.info("返回报文中data的ems状态:{},ems的值:{}",cerficate.getData().get(0).getStatus(),cerficate.getData().get(0).getEms());
                //一旦EMS有值，或者status的状态改变，使用微信发送信息
                if ((!"".equals(cerficate.getData().get(0).getEms()))||(!"10".equals(cerficate.getData().get(0).getStatus().toString()))){
                    //由于是定时任务,给与一个结束发送信息的标识
                    int sendTimes = Integer.valueOf(CalcTime.get(ParamConstant.EMSINFO_SEND_TIME));
                    if (sendTimes >= 5){
                        sendMessage = "时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
                                +"\n邮件信息已查到并发送，程序结束！";
                        new WeChatService().sendMessageWithToken(sendMessage);
                        logger.info("邮件信息已查到并发送，程序结束！");
                        System.exit(0);
                    } else{
                        sendMessage = "证书的信息已变更，及时查看\n"
                                + "时间:"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"\n"
                                + "EMS单号:"+cerficate.getData().get(0).getEms();
                        boolean falg = new WeChatService().sendMessageWithToken(sendMessage);
                        if (!falg){
                            EmailSendService.sendQqEmailforWeChatFail(true,cerficate.getData().get(0).getEms());
                        }
                        CalcTime.update(ParamConstant.EMSINFO_SEND_TIME,String.valueOf(sendTimes+1));
                    }
                }
            }
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
        }

    }

}
